/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.tools.profilers.cpu.art;

import com.android.tools.adtui.model.Range;
import com.android.tools.perflib.vmtrace.VmClockType;
import com.android.tools.perflib.vmtrace.VmTraceParser;
import com.android.tools.profilers.cpu.config.ProfilingConfiguration.TraceType;
import com.android.tools.profilers.cpu.BaseCpuCapture;
import com.android.tools.profilers.cpu.CpuCapture;
import com.android.tools.profilers.cpu.TraceParser;
import java.io.File;
import java.io.IOException;
import org.jetbrains.annotations.NotNull;

/**
 * Receives a binary trace file generated by using ART and parse it into a {@link CpuCapture}
 */
public class ArtTraceParser implements TraceParser {

  /**
   * The message to surface to the user when dual clock information is not available in the trace.
   */
  private static final String DUAL_CLOCK_DISABLED_MESSAGE =
    "This trace only supports Wall Clock Time.<p>" +
    "To view Thread Time, take a new recording after enabling dual clock in Android Studio.";

  private final ArtTraceHandler myTraceHandler = new ArtTraceHandler();

  @Override
  public CpuCapture parse(@NotNull File trace, long traceId) throws IOException {
    VmTraceParser parser = new VmTraceParser(trace, myTraceHandler);
    parser.parse();
    Range range = new Range(
      myTraceHandler.getStartTimeUs(),
      myTraceHandler.getStartTimeUs() + myTraceHandler.getElapsedTimeUs());
    boolean isDualClock = parser.getVmClockType() == VmClockType.DUAL;
    return new BaseCpuCapture(traceId, TraceType.ART, isDualClock, isDualClock ? null : DUAL_CLOCK_DISABLED_MESSAGE, range, myTraceHandler.getThreadsGraph());
  }

  public static boolean verifyFileHasArtHeader(@NotNull File trace) {
    return VmTraceParser.verifyFileHasArtHeader(trace, new ArtTraceHandler());
  }
}
